package org.tpc.printtolls;

import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import org.tpc.printtolls.api.PrintAPI;
import org.tpc.printtolls.model.PrintResult;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

public class HelloController implements Initializable {
    
    @FXML
    private ComboBox<String> printerComboBox;
    
    @FXML
    private TextField paperWidthField;
    
    @FXML
    private TextField paperHeightField;
    
    @FXML
    private TextField copiesField;
    
    @FXML
    private TextField pdfUrlField;
    
    @FXML
    private CheckBox duplexCheckBox;
    
    @FXML
    private ComboBox<String> qualityComboBox;
    
    @FXML
    private TextArea resultTextArea;
    
    @FXML
    private Button printButton;
    
    @FXML
    private Button refreshPrintersButton;
    
    private PrintAPI printAPI;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        printAPI = new PrintAPI();
        
        // 初始化质量选项
        qualityComboBox.setItems(FXCollections.observableArrayList(
            "1 - 草稿", "2 - 普通", "3 - 高质量", "4 - 最高质量"
        ));
        qualityComboBox.getSelectionModel().select(1); // 默认选择普通质量
        
        // 设置默认值
        paperWidthField.setText("210"); // A4宽度
        paperHeightField.setText("297"); // A4高度
        copiesField.setText("1");
        pdfUrlField.setText("https://example.com/sample.pdf");
        
        // 加载打印机列表
        refreshPrinters();
    }

    @FXML
    protected void onPrintButtonClick() {
        try {
            String printerName = printerComboBox.getValue();
            if (printerName == null || printerName.isEmpty()) {
                showError("请选择打印机");
                return;
            }
            
            double paperWidth = Double.parseDouble(paperWidthField.getText());
            double paperHeight = Double.parseDouble(paperHeightField.getText());
            int copies = Integer.parseInt(copiesField.getText());
            String pdfUrl = pdfUrlField.getText();
            
            if (pdfUrl == null || pdfUrl.trim().isEmpty()) {
                showError("请输入PDF URL");
                return;
            }
            
            boolean duplex = duplexCheckBox.isSelected();
            int quality = qualityComboBox.getSelectionModel().getSelectedIndex() + 1;
            
            resultTextArea.setText("正在打印，请稍候...\n");
            
            // 执行打印
            PrintResult result = printAPI.print(printerName, paperWidth, paperHeight, 
                                              copies, pdfUrl, duplex, quality);
            
            // 显示结果
            if (result.isSuccess()) {
                resultTextArea.setText(String.format(
                    "打印成功！\n" +
                    "任务ID: %s\n" +
                    "页数: %d\n" +
                    "份数: %d\n" +
                    "开始时间: %s\n" +
                    "完成时间: %s\n",
                    result.getJobId(),
                    result.getPageCount(),
                    result.getActualCopies(),
                    result.getStartTime(),
                    result.getEndTime()
                ));
            } else {
                resultTextArea.setText("打印失败：" + result.getErrorMessage());
            }
            
        } catch (NumberFormatException e) {
            showError("请输入有效的数字");
        } catch (Exception e) {
            showError("打印过程中发生错误：" + e.getMessage());
        }
    }
    
    @FXML
    protected void onRefreshPrintersButtonClick() {
        refreshPrinters();
    }
    
    @FXML
    protected void onUseA4ButtonClick() {
        paperWidthField.setText("210");
        paperHeightField.setText("297");
    }
    
    @FXML
    protected void onUseA3ButtonClick() {
        paperWidthField.setText("297");
        paperHeightField.setText("420");
    }
    
    @FXML
    protected void onUseLetterButtonClick() {
        paperWidthField.setText("215.9");
        paperHeightField.setText("279.4");
    }
    
    private void refreshPrinters() {
        try {
            List<String> printers = printAPI.getAvailablePrinters();
            printerComboBox.setItems(FXCollections.observableArrayList(printers));
            
            if (!printers.isEmpty()) {
                // 尝试选择默认打印机
                String defaultPrinter = printAPI.getDefaultPrinter();
                if (defaultPrinter != null && printers.contains(defaultPrinter)) {
                    printerComboBox.setValue(defaultPrinter);
                } else {
                    printerComboBox.getSelectionModel().select(0);
                }
            }
            
            resultTextArea.setText(String.format("找到 %d 台打印机：\n%s", 
                                                printers.size(), 
                                                String.join("\n", printers)));
        } catch (Exception e) {
            showError("获取打印机列表失败：" + e.getMessage());
        }
    }
    
    private void showError(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}